package com.wyz.module.config.security.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wyz.module.comm.entity.LoginUserDO;
import com.wyz.module.config.security.mapper.LoginUserMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 无涯子
 * @date 2024/4/20
 */
@Component
public class MyDbUserDetailsManager implements UserDetailsManager, UserDetailsPasswordService {
    @Resource
    private LoginUserMapper mapper;
    @Override
    public UserDetails updatePassword(UserDetails user, String newPassword) {
        return null;
    }

    @Override
    public void createUser(UserDetails user) {
        LoginUserDO loginUser = new LoginUserDO();
        loginUser.setEnabled(true);
        loginUser.setUsername(user.getUsername());
        loginUser.setPassword(user.getPassword());
        mapper.insert(loginUser);
    }

    @Override
    public void updateUser(UserDetails user) {

    }

    @Override
    public void deleteUser(String username) {

    }

    @Override
    public void changePassword(String oldPassword, String newPassword) {

    }

    @Override
    public boolean userExists(String username) {
        return false;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<LoginUserDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StrUtil.isNotBlank(username),LoginUserDO::getUsername,username);
        LoginUserDO user = mapper.selectOne(queryWrapper);
        if(user == null) {
            throw new UsernameNotFoundException(username);
        }else {
            List<GrantedAuthority> roles = new ArrayList<>();
            // User中参数分别是用户名，密码，账号是否可用，账号是否过期，凭证是否过期，账号是否被锁，用户权限
            return new User(user.getUsername(),
                    user.getPassword(),
                    user.getEnabled(),
                    true,
                    true,
                    true,
                    roles);
        }
    }
}
